package com.yunji.news.service.impl;

import cn.hutool.core.util.StrUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.yunji.news.common.ResultCode;
import com.yunji.news.dto.LoginRequest;
import com.yunji.news.dto.LoginResponse;
import com.yunji.news.entity.AdminUser;
import com.yunji.news.entity.School;
import com.yunji.news.mapper.AdminUserMapper;
import com.yunji.news.mapper.SchoolMapper;
import com.yunji.news.service.AuthService;
import com.yunji.news.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 认证服务实现类
 *
 * @author yunji
 * @since 2024-11-23
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {
    
    @Autowired
    private AdminUserMapper adminUserMapper;
    
    @Autowired
    private SchoolMapper schoolMapper;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    // 使用内存存储Token（简化版本，生产环境建议使用Redis）
    private static final Map<Long, String> TOKEN_CACHE = new ConcurrentHashMap<>();
    private static final Map<String, Boolean> TOKEN_BLACKLIST = new ConcurrentHashMap<>();
    
    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        // 查找用户
        AdminUser user = adminUserMapper.selectByUsername(loginRequest.getUsername());
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException("账号已被禁用");
        }
        
        // 验证密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(loginRequest.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 生成Token
        String token = jwtUtils.generateToken(user.getUsername(), user.getId(), user.getRole());
        String refreshToken = jwtUtils.generateRefreshToken(user.getUsername(), user.getId());
        
        // 将Token存储到内存
        TOKEN_CACHE.put(user.getId(), token);
        
        // 更新最后登录信息
        adminUserMapper.updateLastLoginInfo(user.getId(), getClientIp());
        
        // 构造用户信息
        LoginResponse.AdminUserInfo userInfo = new LoginResponse.AdminUserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setRealName(user.getRealName());
        userInfo.setEmail(user.getEmail());
        userInfo.setPhone(user.getPhone());
        userInfo.setRole(user.getRole());
        userInfo.setSchoolId(user.getSchoolId());
        
        // 如果是院校管理员，获取院校名称
        if (user.getSchoolId() != null) {
            School school = schoolMapper.selectById(user.getSchoolId());
            if (school != null) {
                userInfo.setSchoolName(school.getName());
            }
        }
        
        return new LoginResponse(token, refreshToken, userInfo);
    }
    
    @Override
    public LoginResponse refreshToken(String refreshToken) {
        if (!jwtUtils.validateToken(refreshToken)) {
            throw new RuntimeException("刷新Token无效");
        }
        
        String username = jwtUtils.getUsernameFromToken(refreshToken);
        Long userId = jwtUtils.getUserIdFromToken(refreshToken);
        
        if (StrUtil.isBlank(username) || userId == null) {
            throw new RuntimeException("刷新Token无效");
        }
        
        // 查找用户
        AdminUser user = adminUserMapper.selectByUsername(username);
        if (user == null || !user.getId().equals(userId)) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException("账号已被禁用");
        }
        
        // 生成新的Token
        String newToken = jwtUtils.generateToken(user.getUsername(), user.getId(), user.getRole());
        String newRefreshToken = jwtUtils.generateRefreshToken(user.getUsername(), user.getId());
        
        // 更新内存中的Token
        TOKEN_CACHE.put(user.getId(), newToken);
        
        // 构造用户信息
        LoginResponse.AdminUserInfo userInfo = new LoginResponse.AdminUserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setRealName(user.getRealName());
        userInfo.setEmail(user.getEmail());
        userInfo.setPhone(user.getPhone());
        userInfo.setRole(user.getRole());
        userInfo.setSchoolId(user.getSchoolId());
        
        return new LoginResponse(newToken, newRefreshToken, userInfo);
    }
    
    @Override
    public void logout(String token) {
        if (StrUtil.isNotBlank(token)) {
            Long userId = jwtUtils.getUserIdFromToken(token);
            if (userId != null) {
                // 删除内存中的Token
                TOKEN_CACHE.remove(userId);
                
                // 将Token添加到黑名单
                TOKEN_BLACKLIST.put(token, true);
            }
        }
    }
    
    @Override
    public boolean validateToken(String token) {
        if (StrUtil.isBlank(token)) {
            return false;
        }
        
        // 检查Token是否在黑名单中
        if (TOKEN_BLACKLIST.containsKey(token)) {
            return false;
        }
        
        // 验证Token格式
        if (!jwtUtils.validateToken(token)) {
            return false;
        }
        
        // 检查内存中是否存在对应的Token
        Long userId = jwtUtils.getUserIdFromToken(token);
        if (userId == null) {
            return false;
        }
        
        String cachedToken = TOKEN_CACHE.get(userId);
        return token.equals(cachedToken);
    }
    
    /**
     * 获取客户端IP地址（简化实现）
     */
    private String getClientIp() {
        // 这里可以从HttpServletRequest中获取真实IP
        return "127.0.0.1";
    }

    public static void main(String[] args) {
        // 验证密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        System.out.println(encoder.encode("admin123"));
        System.out.println(encoder.matches("admin123","$2a$10$DN6JnkUzpjPFx7sMSPOyy.QKI4fUGd8P/GRpI7kifgCTCIHjZWhfy" ));

    }
}